<template>
  <div class="dialog">
    <el-dialog :title="'疾病记录' + titleText" :visible.sync="showDialog" width="55%" top="0" :close-on-click-modal="false"
      @close="cancel">
      <el-form ref="ruleForm" label-position="left" :model="formData" :rules="rules" class="el-form">
        <el-form-item label="发现疾病: " prop="diseaseBankId" class="w50p">
          <el-select filterable clearable v-model="formData.diseaseBankId" placeholder="请选择" filterable clearable>
            <el-option v-for="(item, index) in diseaseBankList" :label="item.diseaseName" :value="item.diseaseBankId"
              :key="index + 'diseaseBank'" />
          </el-select>
        </el-form-item>
        <el-form-item label="患病数量：" class="w50p" prop="num">
          <el-input v-model="formData.num" type="number" clearable placeholder="请输入病鱼数量">
            <template slot="append">尾</template>
          </el-input>
        </el-form-item>
        <el-form-item label="鱼塘名称: " prop="fishPondId" class="w50p">
          <el-select filterable clearable v-model="formData.fishPondId" placeholder="请选择" filterable clearable @change="pondChange">
            <el-option v-for="(item, index) in pondList" :label="item.pondName" v-show="item.pondName.indexOf('监控') == -1"
              :value="item.fishPondId" :key="index + 'diseaseBank'" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在批次：" prop="productionBatchId" class="w50p">
          <el-select filterable clearable v-model="formData.productionBatchId" placeholder="请先选择鱼塘" filterable clearable
            @change="productionBatchChange">
            <el-option v-for="(item, index) in batchList"
              :label="`${item.mnecode}_${item.varietyName}`"
              :value="item.productionBatchId" :key="index + 'diseaseBank'" :disabled="!item.num" />
          </el-select>
        </el-form-item>
        <el-form-item label="上报人:" prop="discoverStaffName" class="w50p">
          <el-select filterable clearable disabled v-model="formData.discoverStaffName" filterable clearable allow-create
            @change="staffChange">
            <el-option v-for="item of staffList" :key="item.staffId + 'staff'" :label="item.staffName"
              :value="item.staffName" />
          </el-select>
        </el-form-item>
        <el-form-item label="发现日期：" class="w50p" prop="happenTime">
          <el-date-picker v-model="formData.happenTime" type="datetime" placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss" clearable :picker-options="pickerOptions" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="cancelbtn" @click="cancel()">取 消</el-button>
        <el-button type="primary" class="savebtn" @click="save('ruleForm')">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import HealthManagementApi from "@/api/health-management/health-task-management";
import DiseaseBankApi from "@/api/basic-info-manage/diseaseBank";
import BatchMangeApi from "@/api/batch-mange";
import StaffApi from "@/api/basic-info-manage/staff";
import FishPondApi from "@/api/basic-info-manage/fishPond";
import { dialogMixin } from "@/utils/dialogMixin"
let maxTime = null
export default {
  name: '',
  components: {},
  mixins: [dialogMixin],
  props: {
    // 弹框名称
    titleText: {
      type: String,
      default: ""
    },
    nowChanceStau: {
      type: String,
      default: ""
    },
    show: {
      type: Boolean,
      default: false
    },
    editObject: {
      type: [Object],
      default: () => {
        return {}
      }
    },
  },
  data () {
    let checkInt = (rule, value, callback) => {
      if (value) {
        if (Number(value) && value % 1 === 0 && value > 0) {
          callback();
        } else {
          callback(new Error('请输入大于0的数'));
        }
      } else {
        callback(new Error(rule.emptyMsg));
      }
    };
    return {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() < new Date(new Date(maxTime).getTime(new Date(maxTime))) || time.getTime() > new Date().getTime();
        },

        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            if (maxTime < date.getTime() - 3600 * 1000 * 24) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            if (maxTime < date.getTime() - 3600 * 1000 * 24 * 7) {
              picker.$emit('pick', date);
            } else {
              picker.$emit('pick', maxTime);
            }
          }
        }],
      },
      formData: {},
      rules: {
        diseaseBankId: [
          { required: true, message: "请选择发现疾病", trigger: ["change", "blur"] }
        ],
        fishPondId: [
          { required: true, message: "请选择鱼塘名称", trigger: ["change", "blur"] }
        ],
        discoverStaffName: [
          { required: true, message: "请输入员工名称", trigger: ["change", "blur"] }
        ],
        num: [
          { required: true, emptyMsg: "请输入患病鱼数量", trigger: ["change", "blur"], validator: checkInt }
        ],
        productionBatchId: [
          { required: true, message: "请选择批次", trigger: ["change", "blur"] }
        ],
        happenTime: [
          { required: true, message: "请选择发现时间", trigger: ["change", "blur"] }
        ],
      },
      diseaseBankList: [],
      staffList: [],
      batchList: [],
      pondList: [],
      showDialog: this.show
    };
  },

  watch: {
    show (v) {
      maxTime = null
      this.showDialog = v;
    },
    nowChanceStau (v) {
      if (v === 'add') {
        let staffName = sessionStorage.getItem("staffName")
        let staffId = sessionStorage.getItem("staffId")
        let userList = this.staffList.filter(item => {
          return Number(item.staffId) === Number(staffId)
        })
        this.formData = {
          // discoverStaffName: staffId == 1 ? this.staffList[0].staffName : staffName,
          // discoverStaffId: staffId == 1 ? this.staffList[0].staffId : staffId,
          discoverStaffName: userList.length == 0 ? this.staffList[0].staffName : staffName,
          discoverStaffId: userList.length == 0 ? this.staffList[0].staffId : Number(staffId),
          happenTime: this.formatDateTimeMHS(new Date())
        }
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
      if (v === 'edit') {
        this.formData = this.editObject
        // this.pondChange(this.formData.fishPondId)
        BatchMangeApi.queryBatchByPondIdUnComplete({ pondId: this.formData.fishPondId }).then(res => {
          this.batchList = res.data
          this.productionBatchChange(this.editObject.productionBatchId)
        })
      }
    }
  },
  created () {
    maxTime = null
  },
  mounted () {
    this.queryDiseaseBank()
    this.queryStaffApi()
    this.queryPond()
  },
  methods: {
    queryPond () {
      FishPondApi.queryByCondition().then(res => {
        this.pondList = res.data
      })
    },
    queryDiseaseBank () {
      DiseaseBankApi.queryByCondition().then(res => {
        this.diseaseBankList = res.data
      })
    },
    queryStaffApi () {
      StaffApi.queryByCondition().then(res => {
        this.staffList = res.data
      })
    },
    pondChange (e) {
      this.$set(this.formData, 'productionBatchId', undefined);
      BatchMangeApi.queryBatchByPondIdUnComplete({ pondId: e }).then(res => {
        this.batchList = res.data
      })
    },
    productionBatchChange (e) {
      maxTime = ''
      this.formData.happenTime = this.formatDateTimeMHS(new Date())
      this.batchList.find(item => {
        if (item.productionBatchId === e) {
          this.buildDateTime = new Date(item.buildDateTime)
          maxTime = new Date(this.buildDateTime)
          // this.$message()
          // this.formData.happenTime = this.formatDateTimeMHS(maxTime) 
          console.log(maxTime)
        }
      })
    },
    save (formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            this.formData.recoveryStatus = 'UN_RECOVERY'
            HealthManagementApi.edit(this.formData).then(res => {
              if (res.success) {
                this.$message.success("修改成功！");
                this.close()
              } else if (res.errCode === 200) {
                this.$message.error(res.message);
              } else {
                this.$message.error("系统错误,请稍后再试");
              }
            });
          } else if (this.nowChanceStau === "add") {
            this.formData.recoveryStatus = 'UN_RECOVERY'
            HealthManagementApi.add(this.formData).then(res => {
              if (res.success) {
                this.$message.success("添加成功");
                this.close()
              } else if (res.errCode === 200) {
                this.$message.error(res.message);
              } else {
                this.$message.error("系统错误,请稍后再试");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    staffChange (e) {
      this.staffList.find((item) => {
        if (item.staffName === e) {
          this.formData.discoverStaffId = item.staffId
          this.formData.discoverStaffName = item.staffName
          return true
        }
      })
    },
    close () {
      this.$emit("closeDialog");
    },
    cancel () {
      this.$emit("cancelDialog");
    }
  }
};
</script>

<style lang="scss" scoped></style>
